package com.grouponmall.service;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.grouponmall.dao.SQLMapperClient;
import com.grouponmall.model.Deal;

/**
 * @author xueqiang.mi
 * @since 2010-6-2
 */
public class DealServiceImpl implements DealService {

  @Override
  public void addDeal(Deal deal) {
    try {
      SQLMapperClient.data.insert("insertDeal", deal);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void delDeal(String city, String title) {
    try {
      Map<String, Object> params = new HashMap<String, Object>();
      params.put("city", city);
      params.put("title", title);
      SQLMapperClient.data.delete("deleteDeal", params);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  @Override
  @SuppressWarnings("unchecked")
  public List<String> getCities() {
    try {
      List<String> cities = SQLMapperClient.data.queryForList("getCities");
      return cities;
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public Deal getDealById(long id) {
    try {
      Deal deal = (Deal) SQLMapperClient.data.queryForObject("getDealById", id);
      return deal;
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  @SuppressWarnings("unchecked")
  public List<Deal> getDealsByCity(String city, Integer index, Integer pageSize) {
    try {
      List<Deal> deals = SQLMapperClient.data.queryForList("getDealsByCity", city, (index - 1) * pageSize, pageSize);
      return deals;
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  @SuppressWarnings("unchecked")
  public List<Deal> getDealsByPagination(Integer index, Integer pageSize) {
    try {
      List<Deal> deals = SQLMapperClient.data.queryForList("getDealsByPagination", (index - 1) * pageSize, pageSize);
      return deals;
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public List<Deal> getDealsBySource(String source) {
    // TODO: unimplemented
    return null;
  }

  @Override
  @SuppressWarnings("unchecked")
  public List<Deal> getLatestDeals() {
    try {
      List<Deal> deals = SQLMapperClient.data.queryForList("getLatestDeals");
      return deals;
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public void updateDeal(Deal deal) {
    try {
      SQLMapperClient.data.update("updateDeal", deal);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}
